package com.purong.purong.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;

import com.purong.purong.R;
import com.yao.component.pictureselector.MediaSelector;

import java.io.File;
import java.util.List;


/**
 * Created by hzl on 2016/1/14.
 */
public class AvatarPictureDialog extends Dialog {
    private static final int TAKE_BIG_PICTURE = 1000;
    private static final int CROP_BIG_PICTURE_TAKE = 1002;
    private Activity mActivity;
    private File TEMP_PATH;
    private String mFileName;
    private String mFileCropName;
    private OnResultListener mOnResultListener;
    private int mAspectX = 1;
    private int mAspectY = 1;
    public AvatarPictureDialog(Activity context, OnResultListener listener) {
        super(context, R.style.DialogTransparent);
        this.mActivity = context;
        setCanceledOnTouchOutside(true);
        Window window = this.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.dialogWindowAnim);
        TEMP_PATH = getCacheDir(context, "takePicture");
        if (TEMP_PATH.exists()){
            boolean b=deleteDir(TEMP_PATH);
            if (b)
            TEMP_PATH.mkdirs();
        }else {
            TEMP_PATH.mkdirs();
        }
        if (TEMP_PATH.exists()) {
            Log.e("zwj",".......TEMP_PATH_exists");
        }else {
            Log.e("zwj",".......TEMP_PATH_noexists");
        }
        mOnResultListener = listener;
    }
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
           //递归删除目录中的子目录下
            if (children!=null){
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }

        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    public  File getCacheDir(Context context, String uniqueName) {
//        String cachePath = "/storage/sdcard0/Android/data/com.goonpa.gongpa/cache";

//        String cachePath=getExternalCacheDir(context).getPath();
        String cachePath;
        if ( !"mounted".equals(Environment.getExternalStorageState()) && !isExternalStorageRemovable()){
            cachePath=context.getCacheDir().getPath();
        }else {
            cachePath=getExternalCacheDir(context)!=null?getExternalCacheDir(context).getPath():context.getCacheDir().getPath();
        }
//         =?context.getCacheDir().getPath():;
        return new File(cachePath + File.separator + uniqueName);
    }
    public static boolean isExternalStorageRemovable() {
        return Build.VERSION.SDK_INT >= 9?Environment.isExternalStorageRemovable():true;
    }
    public static File getExternalCacheDir(Context context) {
        if(Build.VERSION.SDK_INT >= 8) {
            return context.getExternalCacheDir();
        } else {
            String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
            return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
        }
    }
    public void setAspect(int x, int y) {
        mAspectX = x;
        mAspectY = y;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.dialog_picture, null);
        inflate.setMinimumWidth(10000);
        setContentView(inflate);
        findViewById(R.id.choice_camare).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                camera();
            }
        });
        findViewById(R.id.choice_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                album();

            }
        });
        findViewById(R.id.cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }
    /**
     * 拍照
     */
    public void camera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(TEMP_PATH, mFileName);
        if (file.exists()) {
            file.delete();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        mActivity.startActivityForResult(intent, TAKE_BIG_PICTURE);
    }

    /**
     * 拍照返回裁剪
     *
     *
     */
    private void getSmallFromaAblum(File mFlie) {
        Uri uri = Uri.fromFile(mFlie);
        Uri uri_crop = Uri.fromFile(new File(TEMP_PATH, mFileCropName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        if (mAspectX != -1 && mAspectY != -1) {
            intent.putExtra("aspectX", mAspectX);
            intent.putExtra("aspectY", mAspectY);
        }
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_crop);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, CROP_BIG_PICTURE_TAKE);
    }
    /**
     * 拍照返回裁剪
     *
     *
     */
    private void getSmallFromCamera() {
        Uri uri = Uri.fromFile(new File(TEMP_PATH, mFileName));
        Uri uri_crop = Uri.fromFile(new File(TEMP_PATH, mFileCropName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        if (mAspectX != -1 && mAspectY != -1) {
            intent.putExtra("aspectX", mAspectX);
            intent.putExtra("aspectY", mAspectY);
        }
        intent.putExtra("scale", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_crop);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, CROP_BIG_PICTURE_TAKE);
    }


    public void album() {
        MediaSelector mediaSelector = new MediaSelector(mActivity, MediaSelector.SELECT_PICTURE,1,true, new MediaSelector.onPictureSelectListener() {
                                @Override
                                public void onSelect(List<String> selectPath) {
                                    if (selectPath!=null&&selectPath.size()>0){
                                        getSmallFromaAblum(new File(selectPath.get(0)));
                                    }

                                }

                                @Override
                                public void onCancel() {

                                }
                            });
        mediaSelector.show();
    }
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_BIG_PICTURE:
                    getSmallFromCamera();
//                    if (mOnResultListener != null) {
//                        mOnResultListener.cameraResult(new File(TEMP_PATH,mFileName));
//                    }
                    return true;
                case CROP_BIG_PICTURE_TAKE:

                    if (mOnResultListener != null) {
                        mOnResultListener.cameraResult(new File(TEMP_PATH,mFileCropName));
                    }
                    return true;

            }
        }
        return false;
    }
    @Override
    public void show() {
        super.show();
        mFileName = "temp_" + System.currentTimeMillis() + ".jpg";
        mFileCropName="temp_crop_" + System.currentTimeMillis() + ".jpg";
    }



    public interface OnResultListener {
         void cameraResult(File file);
        void albumSelect(List<String> selectPath);
    }
}
